#!/bin/bash

# 数据备份脚本
set -e

# 配置
BACKUP_DIR="/var/backups/print-ad-system"
DATE=$(date +%Y%m%d_%H%M%S)
MYSQL_CONTAINER="print-ad-mysql"
REDIS_CONTAINER="print-ad-redis"

# 创建备份目录
mkdir -p $BACKUP_DIR

echo "开始备份数据..."

# 备份MySQL数据库
echo "备份MySQL数据库..."
docker exec $MYSQL_CONTAINER mysqldump -u root -p$MYSQL_ROOT_PASSWORD print_ad_system > $BACKUP_DIR/mysql_backup_$DATE.sql

# 备份Redis数据
echo "备份Redis数据..."
docker exec $REDIS_CONTAINER redis-cli BGSAVE
docker cp $REDIS_CONTAINER:/data/dump.rdb $BACKUP_DIR/redis_backup_$DATE.rdb

# 备份上传文件
echo "备份上传文件..."
tar -czf $BACKUP_DIR/uploads_backup_$DATE.tar.gz backend/uploads/

# 备份配置文件
echo "备份配置文件..."
tar -czf $BACKUP_DIR/config_backup_$DATE.tar.gz \
    .env.production \
    docker-compose.yml \
    nginx/ \
    database/conf/

# 清理旧备份（保留7天）
echo "清理旧备份..."
find $BACKUP_DIR -name "*.sql" -mtime +7 -delete
find $BACKUP_DIR -name "*.rdb" -mtime +7 -delete
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

echo "备份完成！备份文件保存在: $BACKUP_DIR"